<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="供应商选择"
    width="80%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="search-section">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="供应商编码">
          <el-input v-model="searchForm.supplierCode" placeholder="请输入供应商编码"></el-input>
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="供应商简称">
          <el-input v-model="searchForm.supplierReferred" placeholder="请输入供应商简称"></el-input>
        </el-form-item>
        <el-form-item label="英文名称">
          <el-input v-model="searchForm.supplierEngName" placeholder="请输入供应商英文名称"></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="searchForm.isEnabled" placeholder="是否启用" clearable style="width: 120px;">
            <el-option label="是" value="是"></el-option>
            <el-option label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      border
      v-loading="loading"
      highlight-current-row
      @current-change="handleCurrentChange"
      height="400"
    >
      <el-table-column type="radio" width="50">
        <template #default="scope">
          <el-radio 
            v-model="selectedRow" 
            :label="scope.row"
            @change="() => handleRadioChange(scope.row)"
          >&nbsp;</el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="supplierCode" label="供应商编码" min-width="120" />
      <el-table-column prop="supplierName" label="供应商名称" min-width="180" />
      <el-table-column prop="supplierReferred" label="供应商简称" min-width="120" />
      <el-table-column prop="supplierLevel" label="供应商等级" min-width="120" />
      <el-table-column prop="supplierRating" label="供应商评分" min-width="120" />
      <el-table-column prop="supplierPhone" label="供应商电话" min-width="120" />
      <el-table-column prop="isLock" label="是否启用" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.isLock === 1 ? 'success' : 'info'">
            {{ scope.row.isLock === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="descs" label="备注" min-width="150" show-overflow-tooltip />
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!selectedRow">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import http from '@/api/http'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'select'])

// 搜索表单
const searchForm = reactive({
  supplierCode: '',
  supplierName: '',
  supplierReferred: '',
  supplierEngName: '',
  isEnabled: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRow = ref(null)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取供应商列表
const getSupplierList = async () => {
  loading.value = true
  try {
    const res = await http.get('/api/Supplier/GetAllSupplierList')
    console.log('供应商API返回数据:', res)

    if (res && Array.isArray(res)) {
      // 根据搜索条件过滤数据
      let filteredData = res.filter(item => {
        const matchCode = !searchForm.supplierCode || 
          String(item.supplierCode || '').toLowerCase().includes(searchForm.supplierCode.toLowerCase())
        const matchName = !searchForm.supplierName || 
          String(item.supplierName || '').toLowerCase().includes(searchForm.supplierName.toLowerCase())
        const matchReferred = !searchForm.supplierReferred || 
          String(item.supplierReferred || '').toLowerCase().includes(searchForm.supplierReferred.toLowerCase())
        const matchEngName = !searchForm.supplierEngName || 
          String(item.supplierEngName || '').toLowerCase().includes(searchForm.supplierEngName.toLowerCase())
        return matchCode && matchName && matchReferred && matchEngName
      })

      // 更新总数
      pagination.total = filteredData.length

      // 分页处理
      const start = (pagination.currentPage - 1) * pagination.pageSize
      const end = start + pagination.pageSize
      tableData.value = filteredData.slice(start, end).map(item => ({
        id: item.id,
        supplierCode: item.supplierCode,
        supplierName: item.supplierName,
        supplierReferred: item.supplierReferred,
        supplierEngName: item.supplierEngName,
        supplierLevel: item.supplierLevel,
        supplierRating: item.supplierRating,
        supplierPhone: item.firstPhone || item.secondPhone,  // 使用第一联系人电话或第二联系人电话
        isLock: item.isLock,
        descs: item.descs
      }))

      console.log('最终显示的数据:', tableData.value)
    } else {
      tableData.value = []
      console.warn('API返回数据为空或格式不正确')
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    ElMessage.error('获取供应商列表失败')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 确保组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载，开始获取供应商数据')
  getSupplierList()
})

// 监听搜索表单变化
watch([
  () => searchForm.supplierCode,
  () => searchForm.supplierName,
  () => searchForm.supplierReferred,
  () => searchForm.supplierEngName
], () => {
  // 重置分页并重新获取数据
  pagination.currentPage = 1
  getSupplierList()
})

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getSupplierList()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  selectedRow.value = null
  pagination.currentPage = 1
  getSupplierList()
}

// 选择行变化
const handleCurrentChange = (row) => {
  selectedRow.value = row
}

// 处理单选框变化
const handleRadioChange = (row) => {
  selectedRow.value = row
  console.log('选中的供应商:', {
    supplierCode: row.supplierCode,
    supplierName: row.supplierName,
    linkMan: row.firstName || row.FirstName,
    phone: row.firstPhone || row.FirstPhone
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  getSupplierList()
}

// 页码改变
const handlePageChange = (val) => {
  pagination.currentPage = val
  getSupplierList()
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  selectedRow.value = null
  handleReset()
}

// 确认选择
const handleConfirm = () => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择供应商')
    return
  }
  
  const supplier = {
    supplierCode: selectedRow.value.supplierCode,
    supplierName: selectedRow.value.supplierName,
    linkMan: selectedRow.value.firstName || selectedRow.value.FirstName,
    phone: selectedRow.value.firstPhone || selectedRow.value.FirstPhone
  }
  
  console.log('确认选择供应商:', supplier)
  emit('select', supplier)
  handleClose()
}
</script>

<style scoped>
.search-section {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding-top: 20px;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
}

:deep(.el-table .el-radio) {
  margin-right: 0;
}

:deep(.el-button + .el-button) {
  margin-left: 10px;
}

:deep(.el-input-group__append) {
  padding: 0;
}

:deep(.el-input-group__append button) {
  margin: 0;
  border: none;
  height: 100%;
  border-radius: 0;
}
</style> 